import {createContext, useReducer} from 'react';

export const FormContext = createContext(null);

const initialState = {
    business: null,
    businessList: [],
    project: null,
    projectList: [],
    path: null,
    pathList: [],
    pathScrollPage: 1,
    // 三期需求指标重要性排序
    sortedTargetTypes: [],
    // 宿主环境
    clientType: 0,
};

const reducer = (state, action) => {
    const {type, data} = action;
    const {
        businessList
    } = state;
    switch (type) {
        case 'changeBusinessList':
            return {
                ...state,
                businessList: data
            };
        case 'changeProjectList':
            return {
                ...state,
                projectList: data,
                path: null,
                pathList: []
            };
        case 'changePathList':
            if (Array.isArray(data)) {
                return {
                    ...state,
                    pathList: data,
                    path: null
                };
            }
            if (data.flag) {
                return {
                    ...state,
                    pathList: data.pathList,
                    pathScrollPage: data.pathScrollPage
                };
            }
            return {
                ...state,
                pathList: data.pathList,
                path: '',
                pathScrollPage: data.pathScrollPage
            };
        case 'changeSorted':
            return {
                ...state,
                sortedTargetTypes: data
            };
        case 'changeBusiness':
            return {
                ...state,
                ...data,
                project: null,
                path: null,
                pathList: [],
                pathScrollPage: 1
            };
        case 'changeProject':
            return {
                ...state,
                ...data,
                path: null,
                pathScrollPage: 1
            };
        case 'changePath':
            return {
                ...state,
                ...data
            };
        case 'changeClientType':
            return {
                ...state,
                clientType: data
            };
        case 'reset':
            // 唯一不重置的是第一步的下拉
            return {
                ...initialState,
                businessList
            };
        default:
            return state;
    }
};

function FormStore(props) {
    const {searchParam} = props;
    const [state, dispatch] = useReducer(reducer, {
        // init value
        ...initialState,
        ...searchParam.analysis
    });
    return [state, FormContext, dispatch];
}

export default FormStore;
